package br.net.woodstock.tickettoride.client.web.taglib;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;

import br.net.woodstock.tickettoride.client.TicketLog;

@SuppressWarnings("rawtypes")
public class AbstractParamsTag extends SimpleTagSupport {

	private Object	value;

	@Override
	public void doTag() throws JspException, IOException {
		AbstractURLTag urlTag = (AbstractURLTag) this.getParent();

		if (this.value == null) {
			TicketLog.getInstance().getLogger().warning("Illegal parameters: null ");
			return;
		}

		if (this.value instanceof Map) {
			Map map = (Map) this.value;
			this.addParameters(urlTag, map);
		} else if (this.value instanceof String) {
			String str = (String) this.value;
			Properties properties = new Properties();
			properties.load(new ByteArrayInputStream(str.getBytes()));
			this.addParameters(urlTag, properties);
		} else {
			TicketLog.getInstance().getLogger().warning("Illegal parameters type " + this.value.getClass().getCanonicalName());
		}
	}

	private void addParameters(final AbstractURLTag urlTag, final Map map) {
		for (Object key : map.keySet()) {
			String name = key.toString();
			Object value = map.get(key);
			urlTag.getParams().put(name, value != null ? value.toString() : null);
		}
	}

	public Object getValue() {
		return this.value;
	}

	public void setValue(final Object value) {
		this.value = value;
	}

}
